package com.huhx.demo.lock;

import java.util.concurrent.CountDownLatch;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkException;

public class ZookeeperLock extends DistributedLock {
	
	private static final String path = "/lock";
	
	private CountDownLatch cdl = null;
	
	private final String hosts = "127.0.0.1:2181";
	
	protected ZkClient client;
	
	public ZookeeperLock() {
		client = new ZkClient(hosts);
	}

	@Override
	protected void waitForLock() {
		IZkDataListener listener = new IZkDataListener() {
			public void handleDataDeleted(String dataPath) throws Exception {
				if (null != cdl) {
					cdl.countDown();
				}
			}
			public void handleDataChange(String dataPath, Object data) throws Exception {
			}
		};
		client.subscribeDataChanges(path, listener);
		//因为是高并发的情况，有可能上面的监听器还没创建完，就有客户端对节点进行操作
		if (client.exists(path)) {
			cdl = new CountDownLatch(1);
			try {
				cdl.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		client.unsubscribeDataChanges(path, listener);
	}

	@Override
	protected boolean tryLock() {
		try {
			client.createEphemeral(path);
			return true;
		} catch (ZkException e) { //TODO 为什么用ZkException
			return false;
		}
	}
}
